import { useChatStore, useGroupStore, useUserStore } from '@/store'
import * as wsApi from '@/utils/wssocket'
import * as enums from '@/utils/enums'
import * as msgType from '@/utils/messageType'
import { findGroupInfo, getPullOfflineMessage } from '@/service/edu/group'

function loadStore() {
  const groupStore = useGroupStore()
  const chatStore = useChatStore()
  const promises = []
  promises.push(groupStore.loadGroup())
  promises.push(chatStore.loadChat())
  return Promise.all(promises)
}

async function loadGroupInfo(id, callback) {
  const groupStore = useGroupStore()
  const group = await groupStore.findGroup(id)
  if (group) {
    callback(group)
  } else {
    findGroupInfo(id).then((res) => {
      groupStore.addGroup(res?.data)
      callback(res?.data)
    })
  }
}

function playAudioTip() {}

function insertGroupMessage(group, msg) {
  const chatStore = useChatStore()
  // 群视频信令
  if (msgType.isRtcGroup(msg.type)) {
    // #ifdef MP-WEIXIN
    // 小程序不支持音视频
    return
  }
  const chatInfo = {
    type: 'GROUP',
    targetId: group.id,
    showName: group.name,
    headImage: group.headImageThumb,
  }
  // 打开会话
  chatStore.openChat(chatInfo)
  // 插入消息
  chatStore.insertMessage(msg)
  // 播放提示音
  playAudioTip()
}

// 退出登录
function exit() {
  const userStore = useUserStore()
  userStore.clearUserInfo()
  uni.reLaunch({ url: '/pages/login/index' })
}
// 私聊消息处理
function handlePrivateMessage(msg) {}

function handleSystemMessage(msg) {}

// 获取离线群消息
function pullGroupOfflineMessage(minId) {
  const chatStore = useChatStore()
  chatStore.setLoadingGroupMsg(true)
  getPullOfflineMessage(minId).catch(() => {
    chatStore.setLoadingGroupMsg(false)
  })
}

// 群聊消息处理
function handleGroupMessage(msg) {
  const chatStore = useChatStore()
  const userStore = useUserStore()
  // 消息加载标志
  if (msg.type == enums.MESSAGE_TYPE.LOADING) {
    chatStore.setLoadingGroupMsg(JSON.parse(msg.content))
    return
  }
  // 消息已读处理
  if (msg.type == enums.MESSAGE_TYPE.READED) {
    // 我已读对方的消息，清空已读数量
    const chatInfo = {
      type: 'GROUP',
      targetId: msg.groupId,
    }
    chatStore.resetUnreadCount(chatInfo)
    return
  }
  // 消息回执处理
  if (msg.type == enums.MESSAGE_TYPE.RECEIPT) {
    // 更新消息已读人数
    const msgInfo = {
      id: msg.id,
      groupId: msg.groupId,
      readedCount: msg.readedCount,
      receiptOk: msg.receiptOk,
    }
    chatStore.updateMessage(msgInfo)
    return
  }
  // 标记这条消息是不是自己发的
  msg.selfSend = msg.sendId === userStore.userInfo.userId
  loadGroupInfo(msg.groupId, (group) => {
    // 插入群聊消息
    if (!group.dissolve) {
      insertGroupMessage(group, msg)
    }
  })
}

// 初始化聊天
export async function initChat() {
  const chatStore = useChatStore()
  const userStore = useUserStore()
  if (userStore.userInfo.token) {
    console.log('wsApi.getIsConnect()=====', wsApi.getIsConnect())
    if (!wsApi.getIsConnect()) {
      await loadStore()
      // 初始化Socket
      wsApi.initSocket()
      // 连接Socket
      wsApi.connectSocket(import.meta.env.VITE_SERVER_IMURL, userStore.userInfo.token)
      // 连接Socket成功
      wsApi.onConnect(() => {
        // 获取离线群消息
        pullGroupOfflineMessage(chatStore.groupMsgMaxId)
      })
      // 监听Socket
      wsApi.onMessage((cmd, msgInfo) => {
        if (cmd === 2) {
          // 异地登录，强制下线
          uni.showModal({
            content: '您已在其他地方登陆，将被强制下线',
            showCancel: false,
          })
          exit()
        } else if (cmd === 3) {
          // 私聊消息
          handlePrivateMessage(msgInfo)
        } else if (cmd === 4) {
          // 群聊消息
          handleGroupMessage(msgInfo)
        } else if (cmd === 5) {
          // 系统消息
          handleSystemMessage(msgInfo)
        }
      })
    }
  }
}
